<template>
  <div class="dialog_box">
    <el-dialog v-model="visible" width="1200px" title="选择产品" @closed="onClose">
      <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
      <ZwTable ref="tableRef" :tabH="'400'" rowIdKey="product_id" class="table-box" :option="tableOption" :rowKey="getRowKey" :fetch-params="state.searchParams" :fetch-api="fetchApi()" @selection-change="handleSelectionChange" @dataChange="dataChange"></ZwTable>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onClose">取消</el-button>
          <el-button @click="onSubmit" type="primary">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
  import { getCateSelect, getProductList } from '@/api/salesleads/common'
  import { CatetList} from '@/api/salesleads/productmanagement/product'
  import Pagination from '@/components/Pagination.vue'
  import { Picture as IconPicture } from '@element-plus/icons-vue'
  import { ElMessage, ElImage, ElIcon } from 'element-plus'
  import { nextTick, ref, watch } from 'vue'
  import { reactive, computed } from 'vue'
  import ZwSearchForm from '@/components/zw/search-form/SearchForm'
  import ZwTable from '@/components/zw/table/Table'
  import { deepCopy } from '@/utils/helper'

  const emit = defineEmits(['submit', 'close'])
  const onClose = () => {
    visible.value = false
    emit('close')
  }
  const visible: any = ref(false)
  const tableRef = ref<any>()
  const PaginationRef = ref<any>()
  const tableData = ref([])
  const checkList = ref([])
  const categoryList = ref([])
  const defaultProps = {
    checkStrictly: false, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: true,
    label: 'name',
    value: 'id'
  }
  const groupOptions = ref([])
  const cateListMap = new Map()
  const getCatetList = async (data: any) => {
    const res = await CatetList(data)
    groupOptions.value = res
    for (const cateItem of res) {
      cateListMap.set(
        cateItem.id,
        cateItem.children.map((item: any) => item.id)
      )
    }
  }
  getCatetList()
  const searchOption = computed(() => {
    return [
      {
        label: '产品品类',
        name: 'category_id',
        value: [],
        type: 'cascader',
        props: defaultProps,
        options: groupOptions.value,
        collapseTags: true,
        collapseTagsTooltip: true,
        onChange: (val: any, formData: any) => {
          const childrenIds = []
          for (const id of val) {
            const ids = cateListMap.get(id)
            if (ids) {
              childrenIds.push(...ids)
            }
          }
          formData?.category_id.splice(0, formData.category_id.length, ...[...val, ...childrenIds])
        }
      },
      {
        label: '产品信息',
        name: 'product_name',
        value: '',
        type: 'input',
        placeholder: '请输入产品名称或编号'
      }
    ]
  })
  const tableOption = [
    {
      type: 'selection',
      width: 55,
      fixed: 'left',
      reserveSelection: true
    },
    {
      prop: 'staff_name',
      label: '产品名称',
      width: 200,
      render({ row }) {
        const slotError = () => (
          <div class="image_slot">
            <ElImage src="/static/file/pic.png" style="width: 48px; height: 48px"></ElImage>
          </div>
        )
        return (
          <div class="product_box">
            <ElImage fit="cover" style="width: 40px; height: 40px" vSlots={{ error: slotError }} src={row.cover}></ElImage>
            <div class="product_right">
              <div class="product_name">{row.product_name}</div>
              <div class="product_no">{row.product_no}</div>
            </div>
          </div>
        )
      }
    },
    {
      prop: 'partment_name',
      label: '规格',
      render({ row, column, index }) {
        return (
          <div vShow={row.spec_type == 2} id={`tableTag${index}`} class={['specificate_list']}>
            {row.specificate_list.map((item: any, i: number) => {
              return (
                <span id={`tag`} class={['btn',item.choose ?'selected': '']} onClick={() => onSelected(row, index, i)}>
                  {item.options_vals}
                </span>
              )
            })}
          </div>
        )
      }
    },
    {
      prop: 'sale_price',
      label: '售卖价',
      width: 100,
      render({ row, column, index }) {
        return <div>￥{row.sale_price}</div>
      }
    }
  ]
  const dataChange = (res: any) => {
    tableData.value = res.data
    console.log(res.data, '数据')
  }
  const getRowKey = (row: any) => {
    return row.id
  }
  const defaultParams = reactive({
    search_value: ''
  })
  const state = reactive({
    searchParams: deepCopy({ ...defaultParams })
  })
  const search = (data: any) => {
    tableRef.value.getTable().clearSelection()
    state.searchParams = { ...deepCopy(data) }
  }
  const reset = (v?: any) => {
    tableRef.value.getTable().clearSelection()
    state.searchParams = deepCopy({ ...v })
  }
  const fetchApi = () => {
    // 获取文件列表
    // getTableH()
    return getProductList
  }
  // 获取表格高度
  const getTableH = () => {
    // nextTick(() => {
    //   tableRef.value.getTableH()
    // })
  }
  const getType = () => {
    getCateSelect().then((res: any) => {
      categoryList.value = res
    })
  }
  getType()
  const handleSelectionChange = (v: any) => {
    checkList.value = deepCopy(v)
  }
  const onSubmit = () => {
    let list: any = []
    tableData.value.map((el: any) => {
      if(checkList.value.some((i: any) => i.product_id == el.product_id)) {
        list.push(el)
      }
    })
    if (list.every((item: any) => item.selected !== '' || item.spec_type == 1)) {
      emit('submit', [...list])
      visible.value = false
    } else {
      ElMessage.warning('请选择所选中产品的规格')
    }
  }
  const toggleSelection = (rows: any) => {
    if (rows) {
      rows.forEach((row: any) => {
        tableRef.value.getTable().toggleRowSelection(row, true)
      })
    } else {
      tableRef.value.getTable().clearSelection()
    }
  }

  const onSelected = (row: any, tableIndex: any, rowIndex: any) => {
    tableData.value[tableIndex].specificate_list.map(el => el.choose = false)
    tableData.value[tableIndex].specificate_list[rowIndex].choose = true
    tableData.value[tableIndex].selected = rowIndex
  }

  defineExpose({
    visible
  })
</script>

<style scoped lang="scss">
  .dialog_box {
    :deep(.el-dialog__header) {
      border-bottom: 1px solid #eaeaea;
    }
    :deep(.el-dialog__body) {
      padding: 15px;
      border-bottom: 1px solid #eaeaea;
    }
    .container {
      padding: 20px;
      background-color: #f9f9f9;
      .form_box {
        display: grid;
        grid-gap: 20px;
        grid-template-columns: 1fr 132px;
        .item_box {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
          grid-gap: 20px;
          .el-form-item {
            :deep(.el-input__inner) {
              width: 100%;
            }
            margin: 0;
            .el-select {
              width: 100%;
            }
            .amount {
              display: grid;
              grid-template-columns: 15px 1fr 15px 1fr;
              grid-gap: 10px;
              .el-input-number {
                width: auto;
              }
            }
            :deep(.el-date-editor--datetime) {
              width: 100%;
            }
            .btn_box {
              text-align: right;
            }
          }
        }
        .btn_box {
          padding: 4px 0;
        }
      }
    }
  }

  .table_box {
    margin-top: 16px;

    :deep(.product_left) {
      width: 48px;
      height: 48px;
      font-size: 48px;
      display: grid;
      place-content: center;
    }
  }
  :deep(.specificate_list) {
    display: grid;
    grid-template-columns: repeat(auto-fit, 100px);
    grid-gap: 4px;
    font-size: 10px;
    -o-user-select: none;
    -moz-user-select: none; /*火狐 firefox*/
    -webkit-user-select: none; /*webkit浏览器*/
    -ms-user-select: none; /*IE10+*/
    -khtml-user-select: none; /*早期的浏览器*/
    user-select: none;
  }
  :deep(.btn) {
    display: flex;
    justify-content: center;
    padding: 4px;
    color: #333333;
    border-radius: 4px;
    border: 1px solid #d8d8d8;
    cursor: pointer;
    &:hover {
      padding: 3px;
      color: #ff6b00;
      border: 2px solid #ff6b00;
    }
  }
  :deep(.selected) {
    padding: 3px;
    color: #ff6b00;
    border: 2px solid #ff6b00;
  }
  :deep(.product_box) {
    display: flex;
    grid-template-columns: 48px 1fr;
    align-items: center;
    grid-gap: 7px;

    .product_right {
      .product_name {
        font-size: 14px;
      }
      .product_no {
        font-size: 10px;
        color: #969696;
      }
    }
  }
  :deep(.el-cascader .el-input){
    height: 36px;
  }
</style>
